#include "stdafx.h"
#include "UniquePort.h"


CUniquePort::CUniquePort()
	: m_nEndPort(0)
	, m_nCurrentPort(0)
	, m_nStartPort(0)
{
	m_mutexPtr = std::make_shared<std::mutex>();
}


CUniquePort::~CUniquePort()
{
}

bool CUniquePort::SetStartPort(unsigned short start, unsigned short end /*= 65535*/)
{
	if (start < 0 || start >65535 || start > end || end > 65535)
	{
		return false;
	}

	m_nStartPort = start;
	m_nEndPort = end;
	//m_nCurrentPort = start;

	return true;
}

bool CUniquePort::GetUsePort(unsigned short& port)
{
	std::unique_lock<std::mutex> lg(*m_mutexPtr);

	if (m_nCurrentPort == 0)
	{
		m_nCurrentPort = m_nStartPort;
		port = m_nCurrentPort++;
		return true;
	}
	else
	{
		if (m_nCurrentPort > m_nEndPort)
		{
			port = 0;
			return false;
		}
		port = m_nCurrentPort++;
		return true;
	}
}

bool CUniquePort::GetOutPutUrl(std::string& url)
{
	std::unique_lock<std::mutex> lg(*m_mutexPtr);

	unsigned short port = 0;
	char szUrl[100] = { 0 };
	if (m_nCurrentPort == 0)
	{
		m_nCurrentPort = m_nStartPort;
		sprintf_s(szUrl, "udp://%s:%d", m_ip.c_str(), m_nCurrentPort++);
		url = szUrl;
		return true;
	}
	else
	{
		if (m_nCurrentPort > m_nEndPort)
		{
			return false;
		}
		sprintf_s(szUrl, "udp://%s:%d", m_ip.c_str(), m_nCurrentPort++);
		url = szUrl;
		return true;
	}
}
